5.2 Numeric and character function


In [ ]:
# 5.2.1 list a summarize table for mathmatic functions
# 5.2.2 list a summarize table for statistic funcitons
# 5.2.3 list a summarize table for probablity funcitons
# d/p/q/r: density/distribution/quantile/random generation
# set.seed for random generation
# MASS.mvrnorm to generate multivariable norm data
# 5.2.4 list a summarize table for character functions
# 5.2.5 Ohter useful functions: length, seq, rep, cut, pretty

In [ ]:
c <- seq(1, 8)
c

In [ ]:
mean(c)

In [ ]:
sd(c)

In [ ]:
x <- seq(1, 8)
n <- length(x)

In [ ]:
meanx <- sum(x)/n
meanx

In [ ]:
ccs <- sum((x - meanx)^2)
ccs

In [ ]:
sdx <- sqrt(ccs / (n-1))
sdx

In [ ]:
x <- pretty(c(-3, 3), 30)
x

In [ ]:
y <- dnorm(x)
plot(x, y, type = "l", xlab = "Normal Deviate", ylab = "Density", yaxs = "i")

In [ ]:
set.seed(20121228)
runif(5)

In [ ]:
set.seed(20121228)
runif(5)

In [ ]:
library(MASS)

In [ ]:
options(digits = 3)
set.seed(1234)
mean <- c(230.7, 146.7, 3.6)
sigma <- matrix(c(15360.8, 6721.2, -47.1,
                     6721.2, 4700.9, -16.5,
                      -47.1,  -16.5,   0.3), nrow=3, ncol=3)
mydata <- mvrnorm(n = 500, mu = mean, Sigma = sigma)
mydata <- as.data.frame(mydata)
names(mydata) <- c("y", "x1", "x2")
str(mydata)
summary(mydata)
head(mydata)

5.2.4 char functions


In [ ]:
paste("A", 1:3, "")

In [ ]:
paste("A", 1:3, "M")

5.3 example


In [ ]:
Student <- c("John Davis", "Angela Williams", "Bullwinkle Moose",
"David Jones", "Janice Markhammer", "Cheryl Cushing",
"Reuven Ytzrhak", "Greg Knox", "Joel England",
"Mary Rayburn")
Math <- c(502, 600, 412, 358, 495, 512, 410, 625, 573, 522)
Science <- c(95, 99, 80, 82, 75, 85, 80, 95, 89, 86)
English <- c(25, 22, 18, 15, 20, 28, 15, 30, 27, 18)
roster <- data.frame(Student, Math, Science, English)

In [ ]:
summary(roster)

In [ ]:
z <- scale(roster[, 2:4])
score <- apply(z, 1, mean)
score
roster <- transform(roster, score = score)
roster

In [ ]:
y <- quantile(score, c(.8, .6, .4, .2))
y

In [ ]:
roster <- transform(roster, grade = score)
roster$grade[roster$score > y[1]] <- "A"
roster$grade[roster$score > y[2] & roster$score <= y[1]] <- "B"
roster$grade[roster$score > y[3] & roster$score <= y[2]] <- "C"
roster$grade[roster$score > y[4] & roster$score <= y[3]] <- "D"
roster$grade[roster$score <= y[4]] <- "F"

roster

5.4 conditional


In [1]:
score <- 1.0
ifelse(score > 0.5, print("Passed"), print("Failed"))


[1] "Passed"
'Passed'

In [2]:
outcome <- ifelse(score > 0.5, "Passed", "Failed")
print(outcome)


[1] "Passed"

In [6]:
feelings <- c("sad", "afraid", "dont know")
for (i in feelings) {
    print(
        switch(i,
              happy = "I am glad",
              afraid = "nothing to fear",
              sad = "cheer up",
              angry = "calm down",
              "haha"
        )
    )
}


[1] "cheer up"
[1] "nothing to fear"
[1] "haha"